﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Events;

namespace YJKDragCurveJig
{
	public class DragCurveJigInterface
	{
		public static bool GetInsertPosition(ExternalCommandData commandData, List<JigEdgeInfo> curveInfos, bool moveCurveInfos, XYZ ptBase, ref XYZ ptPosition)
		{
			List<JigTextInfo> textInfos = new List<JigTextInfo>();
			return DragCurveJigInterface.GetInsertPosition(commandData, curveInfos, moveCurveInfos, textInfos, moveCurveInfos, ptBase, ref ptPosition);
		}

		public static bool GetInsertPosition(ExternalCommandData commandData, List<JigTextInfo> textInfos, bool moveTextInfos, XYZ ptBase, ref XYZ ptPosition)
		{
			List<JigEdgeInfo> curveInfos = new List<JigEdgeInfo>();
			return DragCurveJigInterface.GetInsertPosition(commandData, curveInfos, moveTextInfos, textInfos, moveTextInfos, ptBase, ref ptPosition);
		}

		public static bool GetInsertPosition(ExternalCommandData commandData, List<JigEdgeInfo> curveInfos, bool moveCurveInfos, List<JigTextInfo> textInfos, bool moveTextInfos, XYZ ptBase, ref XYZ ptPosition)
		{
			commandData.Application.ApplicationClosing += DragCurveJigInterface.AppClosingEventOperation;
			JigCreator jigCreator = new JigCreator(commandData);
			string text = "";
			jigCreator.Initialize(curveInfos, textInfos, ptBase, ref text);
			if (!jigCreator.Do(ref ptPosition))
			{
				commandData.Application.ApplicationClosing -= DragCurveJigInterface.AppClosingEventOperation;
				return false;
			}
			Transform matrix = RevitVersionFuncs.CreateTranslation(ptPosition - ptBase);
			if (moveCurveInfos)
			{
				for (int i = 0; i < curveInfos.Count; i++)
				{
					curveInfos[i].TransformSelf(matrix);
				}
			}
			if (moveTextInfos)
			{
				for (int j = 0; j < textInfos.Count; j++)
				{
					textInfos[j].TransformSelf(matrix, false);
				}
			}
			commandData.Application.ApplicationClosing -= DragCurveJigInterface.AppClosingEventOperation;
			return true;
		}

		private static void AppClosingEventOperation(object sender, ApplicationClosingEventArgs e)
		{
		}

		[DllImport("user32.dll")]
		public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

		private static void CancelRevitOperate()
		{
			int bVk = 27;
			int dwFlags = 0;
			int dwFlags2 = 2;
			DragCurveJigInterface.keybd_event((byte)bVk, 0, dwFlags, 0);
			DragCurveJigInterface.keybd_event((byte)bVk, 0, dwFlags2, 0);
		}
	}
}
